#!/usr/bin/python
"""
    File:       configure.py
    Brief:      read/write from/to .ini/.xml files
    Author:     Xu Qiang
    Version:    1.0
    Date:       2017 - 4 - 18
"""

import os
from Log import LogE
import xml.dom.minidom


class iniManager( object ):
    '''
    read/write configure data to ini format file
    '''
    def __init__( self, filename = None, readOnly = True, autoSave = True ):
        self.__dict__['m_file'] = filename
        self.__dict__['m_readOnly'] = readOnly
        self.__dict__['m_autoSave'] = autoSave
        self.__dict__['m_lines'] = []
        if filename != None:
            self.load( filename )

    def __del__( self ):
        if self.__dict__['m_file'] != None and self.__dict__['m_autoSave']:
            self.save()

    def __getattr__( self, attr ):
        for line in self.__dict__['m_lines']:
            if isinstance( line, list ):
                if attr.strip() == line[0]:
                    return line[1]
        return None

    def __setattr__( self, attr, value ):
        for line in self.__dict__['m_lines']:
            if isinstance( line, list ):
                if attr.strip() == line[0]:
                    line[1] = value
                    return
        self.__dict__["m_lines"].append( [attr, value] )

    def load( self, file ):
        self.__dict__['m_file'] = file
        self.__dict__['m_lines'] = []
        accessFlag = os.access( self.__dict__['m_file'], os.R_OK )
        if not accessFlag:
            #LogW.write( "No permission to access file: %s" % self.__dict__['m_file'] )
            return
        try:
            fileHandle = open( self.__dict__['m_file'], "r" )
        except Exception, e:
            pass#LogW.write( "Open file: %s failed by %s" % ( self.__dict__['m_file'], str( e ) ) )
        try:
            for line in fileHandle:
                if len( line ) > 1 and line[0] != "#":
                    lineList = line.split( "=" , 1 )
                    lineList[0] = lineList[0].strip()
                    lineList[1] = lineList[1].strip()
                    self.__dict__['m_lines'].append( lineList )
                else:
                    self.__dict__['m_lines'].append( line )
        except Exception, e:
            pass#LogW.write( "iniManager.load(%s) failed by %s" % ( self.__dict__['m_file'], str( e ) ) )
        finally:
            fileHandle.close()

    def saveAs( self, fileName ):
        assert isinstance( fileName, type("string") )
        self.save( fileName )

    def save( self, fileName = None ):
        if fileName == None and not self.__dict__["m_readOnly"]:
            fileName = self.__dict__['m_file']
        if fileName == None:
            return
        if not os.access( fileName, os.W_OK ):
            LogE.write( "No permission to write to fileName: %s" % fileName )
            return

        try:
            fileHandle = open( fileName, "w+" )
        except Exception, e:
            LogE.write( "Open fileName: %s failed by %s" % ( fileName, str( e ) ) )

        try:
            for line in self.__dict__["m_lines"]:
                if isinstance( line, list ):
                    fileHandle.write( line[0] + "=" + line[1] + "\\n" )
                else:
                    fileHandle.write( line )
        except Exception, e:
            pass#LogW.write( "iniManager.save(%s) failed by %s" % ( self.__dict__['m_file'], str( e ) ) )
        finally:
            fileHandle.close()


def removeBlankLine( filename ):
    '''
    remove blank line of the given file
    '''
    fileHandle = open( filename, "r" )
    allLines = []
    for line in fileHandle:
        if line.strip() != "":
            allLines.append( line )
    fileHandle.close()
    fileHandle = open( filename, "w" )
    for line in allLines:
        fileHandle.write( line )
    fileHandle.close()

def saveDomToFile( dom, filename ):
    '''
    write dom documetion node to file
    '''
    fileHandle = open( filename, 'w' )
    dom.writexml( fileHandle, '', ' ', '\n' )
    fileHandle.close()
    removeBlankLine( filename )

class xmlManager( object ):
    def __init__( self, filename = None, readOnly = True, autoSave = False ):
        self.m_file = filename
        self.m_readOnly = readOnly
        self.m_autoSave = autoSave
        self.m_dom = None
        if filename != None:
            self.load( filename )

    def __del__( self ):
        if self.m_file != None and self.m_autoSave:
            self.saveAs( self.m_file )

    def __getattr__( self, attr ):
        rootDom = self.m_dom.documentElement
        targetDoms = rootDom.getElementsByTagName( attr )
        if len( targetDoms ) == 0:
            return None
        elif len( targetDoms ) > 1:
            raise "class xml file wrong"
        else:
            return targetDoms[0]

    def load( self, fileName ):
        self.m_file = fileName
        self.m_dom = None
        self.m_dom = xml.dom.minidom.parse( fileName )


    def saveAs( self, fileName = None ):
        if fileName == None:
            fileName = self.m_file
        if fileName == None:
            return
        if not os.access( fileName, os.W_OK ):
            LogE.write( "No permission to write to fileName: %s" % fileName )
            return
        if self.m_dom != None:
            saveDomToFile( self.m_dom, fileName )

